package com.picturehistory.core.jersey.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.jdo.support.JdoDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.picturehistory.core.jersey.exception.InvalidUserException;
import com.picturehistory.core.jersey.model.Article;
import com.picturehistory.core.jersey.model.User;
import com.picturehistory.core.jersey.util.PMF;

public class ArticleDAOJDOImpl extends JdoDaoSupport implements ArticleDAO {
	
	private final Logger logger = LoggerFactory.getLogger(ArticleDAOJDOImpl.class);
	
	@Transactional
	public Article getArticleById(long id) throws DataAccessException {
		
		Article ret = getJdoTemplate().getObjectById(Article.class, id);
		return (Article) getJdoTemplate().detachCopy(ret);
	}
	
	public long storeArticle(User user, Article at) throws DataAccessException {
		
		Date now = new Date();
		at.setCreated(now); at.setModified(now);
		
		getJdoTemplate().makePersistent(at);
		logger.info("successfully stored an Article object: " + at);
		
		//update user
		logger.info("an Article object is now assigned a numeric id: " + at.getNumericId());
		return at.getNumericId();
	}
	
	@Transactional
	public Article updateArticle(User user, Article at, long id) 
	throws DataAccessException, InvalidUserException {
		
		
		Article target = getJdoTemplate().getObjectById(Article.class, id);
		logger.info("target article has been found with id=" + id);
		
		
		
		logger.info("modify article");
		target.setTitle(    at.getTitle()   );
		target.setBody(     at.getBody()    );
		target.setHashTag(  at.getHashTag() );
		target.setModified( new Date()      );
		
		logger.info("store back the article");
		getJdoTemplate().makePersistent(target);
		
		return (Article) getJdoTemplate().detachCopy(target);
	}

	@Transactional
	public List<Article> loadArticleByXY(Integer x, Integer y) throws DataAccessException {
		Map<String, Integer> values = new HashMap<String, Integer>();
		values.put("paramX", x);
		values.put("paramY", y);
		
		List<Article> ret = (List<Article>) getJdoTemplate().find(
				Article.class, 
				"x==paramX && y==paramY",
				"Integer paramX, Integer paramY",
				values);

		return (List<Article>) getJdoTemplate().detachCopyAll(ret);
	}

}
